﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO.IsolatedStorage;
using System.IO;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;

namespace DSVISUAL
{
    public class StorageService
    {
        private StorageService()
        { }
        private static StorageService _instance;
        public static StorageService Instance
        {
            get { if (_instance == null) _instance = new StorageService(); return _instance; }
        }
        public void SaveData(object data)
        {
            IsolatedStorageFile isoStore = IsolatedStorageFile.GetStore(IsolatedStorageScope.User | IsolatedStorageScope.Domain | IsolatedStorageScope.Assembly, null, null);
            using (IsolatedStorageFileStream isoStream = new IsolatedStorageFileStream("Setting.bin", FileMode.Create, isoStore))
            {
                var bytes = Encoding.UTF8.GetBytes(Newtonsoft.Json.JsonConvert.SerializeObject(data));
                isoStream.Write(bytes, 0, bytes.Length);
            }
        }

        public T GetData<T>()
        {
            IsolatedStorageFile isoStore = IsolatedStorageFile.GetStore(IsolatedStorageScope.User | IsolatedStorageScope.Domain | IsolatedStorageScope.Assembly, null, null);
            try
            {
                using (StreamReader sr = new StreamReader(new IsolatedStorageFileStream("Setting.bin", FileMode.Open, isoStore)))
                {
                    var str = sr.ReadToEnd();
                    return Newtonsoft.Json.JsonConvert.DeserializeObject<T>(str);

                }
            }
            catch
            {
                return default(T);
            }
        }
    }
}
